﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using Super.Entities;
using Super.Infrastructure;

namespace Super.DomainService
{
    public class DicService : BaseService<ChineseDictionary>
    {
        private readonly DbContextAdapter _adp;
        private readonly BaseService<ChineseDictionary> _dicService;
        private static List<ChineseDictionary> _chineseDictionaries = new List<ChineseDictionary>();
        public DicService(DbContextAdapter adp)
            : base(adp)
        {
            _adp = adp;
            _dicService = new BaseService<ChineseDictionary>(adp);
        }

        /// <summary>
        /// 获取汉字首字母
        /// </summary>
        /// <param name="strText"></param>
        /// <returns></returns>
        public string GetChineseFirstSpell(string strText)
        {
            int len = strText.Length;
            string myStr = "";
            for (int i = 0; i < len; i++)
            {
            
                Regex regChina = new Regex("^[^\x00-\xFF]");
                if (regChina.IsMatch(strText.Substring(i, 1)))
                {
                    if (!string.IsNullOrEmpty(strText.Substring(i, 1)))
                    {
                        var str = getCharacter(strText.Substring(i, 1));
                        if (str != null)
                        {
                            myStr += str.PY.Substring(0, 1).ToUpper();
                        }
                        else
                        {
                            myStr += "*";
                        }
                    }

                }
                else
                {
                    myStr += strText.Substring(i, 1);
                }

            }
            return myStr;
        }

        /// <summary>
        /// 根据汉字字符串查找汉字实体
        /// </summary>
        /// <param name="nchar"></param>
        /// <returns></returns>
        public ChineseDictionary getCharacter(string nchar)
        {
            if (_chineseDictionaries.Count <= 0)
            {
                _chineseDictionaries = _dicService.Repository.GetAll().ToList();
            }

            return _chineseDictionaries.Where(a => a.ZI == nchar).FirstOrDefault();

        }

    }
}
